const express = require('express');
const { User } = require('../models');
const { Op } = require('sequelize');
const router = express.Router();
const jwt = require('jsonwebtoken');
const SECRET_KEY = 'YOUR_SECRET_KEY';
router.post('/login/account', async (req, res) => {
    const { username, password } = req.body;
    if (!username || !password) {
        return res.status(400).send({
            status: 'error',
            message: 'Both username and password are required.'
        });
    }
    const user = await User.findOne({
        where: {
            username
        }
    });
    if (!user || user.password !== password) {
        return res.status(404).send({
            status: 'error',
            message: 'Invalid username or password.'
        });
    }
    const token = jwt.sign({
        userid: user.userid,
        username: user.username
    }, SECRET_KEY, {
        expiresIn: '1h'
    });
    res.send({
        status: "ok",
        type: "account",
        token,
        currentAuthority: "admin"
    });
});
router.post('/login/outLogin', (req, res) => {
    res.send({
        data: {},
        success: true
    });
});

router.get('/currentUser', async (req, res) => {
    const { authorization } = req.headers;
    if (!authorization) {
        return res.status(403).send({
            status: 'error',
            message: 'Token not provided.'
        });
    }
    const token = authorization.replace('Bearer ', '');
    try {
        const { userid } = jwt.verify(token, SECRET_KEY);
        const user = await User.findOne({
            where: {
                userid
            }
        });
        if (!user) {
            return res.status(404).send({
                success: false,
                message: 'User not found.'
            });
        }
        res.send({
            success: true,
            data: {
                name: user.name,
                avatar: user.avatar,
                userid: user.userid,
                email: user.email,
                signature: user.signature,
                title: user.title,
                group: user.group,
                notifyCount: user.notifyCount,
                unreadCount: user.unreadCount,
                country: user.country,
                access: user.access,
                geographic: {
                    province: {
                        label: user.province,
                        key: "330000"
                    },
                    city: {
                        label: user.city,
                        key: "330100"
                    }
                },
                address: user.address,
                phone: user.phone
            }
        });
    } catch (error) {
        return res.status(403).send({
            status: 'error',
            message: 'Invalid token.'
        });
    }
});


router.get('/user', async (req, res) => {
    const current = parseInt(req.query.current);
    const pageSize = parseInt(req.query.pageSize);
    let whereClause = {};
    let orderClause=[];
    if (req.query.sorter) {
        const sorter = JSON.parse(req.query.sorter);
        const fields = Object.keys(sorter);
        const orders = fields.map(field => sorter[field] === 'descend' ? 'DESC' : 'ASC');
        orderClause = fields.map((field, index) => [field, orders[index]]);
    }
    if (req.query.filter) {
        const filter = JSON.parse(req.query.filter);
        Object.keys(filter).forEach(field => {
            if (filter[field] !== null) {
                whereClause[field] = {
                    [Op.in]: filter[field]
                };
            }
        });
    }
    if (req.query.name) {
        whereClause.name = {
            [Op.like]: `%${req.query.name}%`
        };
    }
    if (req.query.username) {
        whereClause.username = {
            [Op.like]: `%${req.query.username}%`
        };
    }
    if (req.query.email) {
        whereClause.email = {
            [Op.like]: `%${req.query.email}%`
        };
    }
    if (req.query.access) {
        whereClause.access = {
            [Op.like]: `%${req.query.access}%`
        };
    }
    try {
        const total = await User.count({
            where: whereClause
        });
        const users = await User.findAll({
            where: whereClause,
            limit: pageSize,
            offset: (current - 1) * pageSize,
            order: orderClause
        });
        res.status(200).json({
            data: users,
            total: total,
            success: true,
            pageSize: pageSize,
            current: current
        });
    } catch (err) {
        console.log(err);
        res.status(500).json({
            success: false,
            message: 'Error retrieving users'
        });
    }
});


router.post('/user', async (req, res) => {
    try {
        const user = await User.create(req.body);
        res.json(user);
    } catch (err) {
        console.log(err);
        res.status(500).json({
            message: 'Error creating user'
        });
    }
});

router.put('/user', async (req, res) => {
    try {
        let {
            userid,
            ...user
        } = req.body;
        const updatedUser = await User.update(user, {
            where: {
                userid
            }
        });
        if (updatedUser[0] === 0) {
            return res.status(404).json({
                message: 'User not found'
            });
        }
        res.json({
            success: true
        });
    } catch (err) {
        console.log(err);
        res.status(500).json({
            message: 'Error updating user'
        });
    }
});

router.delete('/user', async (req, res) => {
    try {
        const rowsDeleted = await User.destroy({
            where: {
                userid: req.body.userid
            }
        });
        if (rowsDeleted === 0) {
            return res.status(404).json({
                message: 'User not found'
            });
        }
        res.json({
            success: true
        });
    } catch (err) {
        res.status(500).json({
            message: 'Error deleting user'
        });
    }
});

module.exports = router;